package cn.ainit.sys.ui.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.sun.org.apache.bcel.internal.generic.IF_ACMPEQ;

import cn.ainit.common.ReturnObject;
import cn.ainit.sys.ds.cloumns.QueryJsonDao;
import cn.ainit.sys.framework.entity.SysButtons;
import cn.ainit.sys.framework.entity.SysColumns;
import cn.ainit.sys.pages.config.entity.ConfigFunctions;
import cn.ainit.sys.pages.config.entity.ConfigObject;
import cn.ainit.sys.pagescript.entity.ReceiveParam;
import cn.ainit.sys.query.datastore.DataStore;
import cn.ainit.sys.query.entity.QueryButton;
import cn.ainit.sys.query.entity.QueryColumn;
import cn.ainit.sys.query.entity.QueryJson;
import cn.ainit.sys.ui.buttons.FormButtons;
import cn.ainit.sys.ui.entity.InputFormReturnObject;
import cn.ainit.sys.ui.entity.UIObject;
import cn.ainit.sys.ui.forms.Columns;

/***
 * 入单界面设计
 * 
 * @author xuzq
 */

@Controller
@RequestMapping("/sys")
public class UIController {

	private UIService uiService;
	private QueryJsonDao qDao;

	@Resource
	public void setqDao(QueryJsonDao qDao) {
		this.qDao = qDao;
	}

	@Resource
	public void setUiService(UIService uiService) {
		this.uiService = uiService;
	}

	/**
	 * 跳转到入单界面(主表)
	 * 
	 * @param formType
	 *            对应的界面字段 formObjId 这个对象的一些信息
	 * @param request
	 * @return
	 */
	@RequestMapping("/inputForms")
	public String addObjectForm(InputFormReturnObject informObj,
			HttpServletRequest request) {
		try {
			// request.setAttribute("lineColT", 4);//查找对象，将值传入
			// request.setAttribute("formObj",
			// uiService.fingFormObjById(formObjId));
			// request.setAttribute("formType", formType);
			request.setAttribute("buttons", uiService.findAllButtons(informObj
					.getFormType()));
			// request.setAttribute("columns",
			// uiService.getColumnsById(formType));
			request.setAttribute("informObj", informObj);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "/homepages/input/inputform";
	}

	/***
	 * 获取入单界面信息
	 * 
	 * @param dsid
	 * @param request
	 * @return
	 */
	@RequestMapping("/getUIColumns")
	@ResponseBody
	public InputFormReturnObject getUIColumns(InputFormReturnObject informObj,
			HttpServletRequest request) {
		List<Columns> columns = new ArrayList<Columns>();
		try {
			// UIObject uiObject = null;
			// 查找对象的显示 等信息
			// formObjId对象类型 default:入单框 info入单详细信息
			// mdefault：主明细入单表 minfo主明细信息
			// V1.0.1 根据informObj (configId) 查询对象
			// if (informObj.getFormObjId() == null ||
			// informObj.getFormObjId().equals("")) {
			// informObj.setFormObjId("default");
			// }
			// uiObject =
			// uiService.findFormObjById(informObj.getFormType(),informObj.getFormObjId());//ds_id
			// dbi
			// 方法变量

			// 传入configId得到ConfigOnject
			ConfigObject configObject = uiService.findConfigObj(informObj
					.getConfigId());

			// 根据functionId 得到所有的方法没有就算了
			List<String> funList = new ArrayList<String>();
			if (configObject != null) {
				// 字段样式
				informObj
						.setLineCol((configObject.getLineCol() != null && configObject
								.getLineCol() > 0) ? configObject.getLineCol()
								: 4);
				// 方法集合
				ConfigFunctions configFunctions = uiService
						.findConfigFunsById(informObj.getFunsId());
				if (configFunctions != null
						&& configFunctions.getFuncContents() != null
						&& !configFunctions.getFuncContents().trim().equals("")) {
					String[] funArr = configFunctions.getFuncContents().split(
							";");
					for (int i = 0; i < funArr.length; i++) {
						funList.add(funArr[i]);
					}
				}
			} else {
				informObj.setLineCol(4);
			}
			informObj.setFunctions(funList);
			informObj.setColumns(uiService.getColumnsById(configObject
					.getUiColDsId()));
			informObj.setButtons(uiService.findAllButtons(configObject
					.getUiButnId()));
		} catch (Exception e) {
			e.printStackTrace();
		}
		return informObj;
	}

	/***
	 * 获取相似信息
	 * 
	 * @param inputType
	 * @param str
	 * @param request
	 * @return
	 */
	@RequestMapping("/getSameInfoStr")
	@ResponseBody
	public List<String> getSameInfoStr(String inputType, String str,
			HttpServletRequest request) {
		String tableName = "";
		String columnName = "";
		List<String> sameStringList = new ArrayList<String>();
		try {
			if ((inputType.indexOf(".") >= 0)
					&& (inputType.split("\\.").length == 2)) {
				tableName = inputType.split("\\.")[0];
				columnName = inputType.split("\\.")[1];
				sameStringList = uiService.getSameInfoStr(tableName,
						columnName, str);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return sameStringList;
	}

	/***
	 * 跳到编辑表格界面 -- > 界面设计，添加字段 （未启用）
	 * 
	 * @return
	 */
	@RequestMapping("/editform")
	public String editForms() {
		return "/homepages/sys/editform";
	}

	/***
	 * 拼接下拉框选项
	 * 
	 * @return
	 */
	@RequestMapping("/loadOptions")
	@ResponseBody
	public Object loadOptions(String dsid, String config,
			HttpServletRequest request) {
		// List<SelectOptions> selectOptions = new ArrayList<SelectOptions>();
		Object object = null;
		if (config == null) {
			config = "";
		}
		try {
			System.out.println(dsid);
			DataStore dataStore = uiService.getDataStoreById(dsid);
			String sqlC = "";
			if (config != null && !config.equals("null") && !config.equals("")) {
				if (config.indexOf(";") >= 0) {
					String[] configArr = config.split(";");
					StringBuffer tmpC = new StringBuffer();
					for (int i = 0; i < configArr.length; i++) {
						tmpC.append(configArr[i]);
						if (i < configArr.length - 1) {
							tmpC.append("',");
						}
					}
					config = tmpC.toString();
				}

				sqlC = " where " + dataStore.getConfigCln() + " in ('" + config
						+ "')";
			}
			if (dataStore != null) {
				object = uiService.querySelectOptions(dataStore.getSqlText(),
						sqlC, dataStore.getShowPK(), dataStore.getShowName(),
						dataStore.getPageRows());
			} else {
				throw new RuntimeException("找不到DS");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return object;
	}

	/**
	 * 未完待续
	 * 
	 * @param column
	 * @param request
	 * @throws Exception
	 */
	@RequestMapping("/saveCol")
	@ResponseBody
	public void addCol(Columns column, HttpServletRequest request)
			throws Exception {

	}

	/**
	 * 添加列的方法
	 * 
	 * @param column
	 * @param request
	 * @return
	 * @throws Exception
	 */
	// 详细信息界面
	@RequestMapping("/saveColumn")
	@ResponseBody
	public int saveColumn(String formId, Columns column,
			HttpServletRequest request) throws Exception {
		int i = 0;
		try {
			column.setDsid(formId);
			if (this.uiService.addColumns(column)) {
				i = 1;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return i;
	}

	/**
	 * 添加按钮
	 * 
	 * @param butns
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/saveButns")
	@ResponseBody
	public int saveButns(String formId, FormButtons butns,
			HttpServletRequest request) throws Exception {
		int i = 0;
		try {
			butns.setDsid(formId);
			// if(this.uiService.addButns(butns)){
			i = 1;
			// }
		} catch (Exception e) {
			e.printStackTrace();
		}
		return i;
	}

	@SuppressWarnings("unchecked")
	@RequestMapping("/saveSql")
	@ResponseBody
	public QueryJson saveSql(DataStore store, HttpServletRequest request)
			throws Exception {
		QueryJson queryJson = new QueryJson();
		List<String> list = new ArrayList<String>();
		List<Object> queryCol = new ArrayList<Object>();
		List<SysColumns> columns = new ArrayList<SysColumns>();
		try {
			boolean flag = false;
			String sql = "";
			list = uiService.callBackSql(store.getSqlText());
			flag = uiService.saveQueryCol(list, store.getDsId());
			sql = "select ds_id ,Name ,Coln_Name from sys_columns  where ds_id= '"
					+ store.getDsId() + "'";
			if (flag) {
				uiService.saveDS(store);
			}
			queryCol = (List<Object>) uiService.queryColBySql(sql);// rows
			columns = uiService.queryColumns("columnSet");
			queryJson.setRows(queryCol);// rows
			queryJson.setColumns(columns);// columns
			queryJson.setExtendinfo(store.getDbi());
			return queryJson;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 保存sql
	 * 
	 * @param sqlText
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping("/saveSqls")
	@ResponseBody
	public QueryJson saveSqls(DataStore store, HttpServletRequest request)
			throws Exception {
		QueryJson queryJson = new QueryJson();
		List<String> list = new ArrayList<String>();
		List<Object> queryCol = new ArrayList<Object>();
		List<SysColumns> columns = new ArrayList<SysColumns>();
		try {
			boolean flag = false;
			String sql = "";
			list = uiService.callBackSql(store.getSqlText());
			if (store.getDbi().equals("sys_query")) {
				flag = uiService.saveQueryCol(list, store.getDsId());
				sql = "select ds_id ,Name ,Coln_Name from sys_query_columns  where ds_id= '"
						+ store.getDsId() + "'";
			} else if (store.getDbi().equals("sys_ui")) {
				flag = uiService.saveQueryUICol(list, store.getDsId());
				sql = "select ds_id ,Name ,Coln_Name from sys_ui_forms_columns  where ds_id= '"
						+ store.getDsId() + "'";
			} else if (store.getDbi().equals("sys_select")) {
				flag = true;
			}

			if (flag) {
				uiService.saveDS(store);
			}
			queryCol = (List<Object>) uiService.queryColBySql(sql);// rows
			columns = uiService.queryColumns("columnSet");
			queryJson.setRows(queryCol);// rows
			queryJson.setColumns(columns);// columns
			queryJson.setExtendinfo(store.getDbi());
			return queryJson;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 根据sql修改数据列 （修改UI的）
	 * 
	 * @param sqlText
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/updateUI")
	@ResponseBody
	public int updateQU(Columns UIColumn, HttpServletRequest request)
			throws Exception {
		int i = 0;
		try {
			if (uiService.upQueryColn(UIColumn)) {
				i = 1;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return i;
	}

	/**
	 * 根据sql修改数据列（修改Query的）
	 * 
	 * @param sqlText
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/updateQU")
	@ResponseBody
	public int updateQU(QueryColumn queryColumn, HttpServletRequest request)
			throws Exception {
		int i = 0;
		try {
			if (uiService.upQuCol(queryColumn)) {
				i = 1;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return i;
	}

	/**
	 * 添加UI按钮
	 * 
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/saveUI")
	@ResponseBody
	public int saveUIButns(SysButtons uiButtons, HttpServletRequest request)
			throws Exception {
		int i = 0;
		try {
			boolean flag = uiService.addButns(uiButtons);
			if (flag) {
				i = 1;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return i;
	}

	/**
	 * 添加Query按钮
	 * 
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/saveQuery")
	@ResponseBody
	public int saveQueryButns(QueryButton queryButton,
			HttpServletRequest request) throws Exception {
		int i = 0;
		try {
			boolean flag = uiService.addQueryButns(queryButton);
			if (flag) {
				i = 1;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return i;
	}

	// 更新数据
	@RequestMapping("/updateColumns")
	@ResponseBody
	public ReturnObject updateButClick(ReceiveParam params, String sysTName,
			String config, HttpServletRequest request) {
		try {
			ReturnObject returnObject = new ReturnObject();
			// Map<String,Columns> colnMap = new
			// HashMap<String,Columns>();//数据库中有属性、可更新字段
			// Map<String,Columns> readOnlyColnMap = new
			// HashMap<String,Columns>();//数据库中不可更新字段
			String[] paramsKandV = params.getSqlParams();// 界面参数
			// b.将界面字段遍历 所有的字段 有则留 添加到相应的字段
			// 拼接条件语句 update tableName set k1=v1,k2=v2 where sk1=v1
			StringBuffer keyStr = new StringBuffer("");// sql值字段+占位符 a=?,b=?
			StringBuffer keyValues = new StringBuffer("");// sql值字段值的字符串 A|B
			StringBuffer whereKey = new StringBuffer("");// 条件 ds_id=?,name=?
			StringBuffer whereKeyValues = new StringBuffer("");// 条件值的字符串
																// DSID|NAME
			String[] tmpKV = new String[2];
			for (int i = 0; i < paramsKandV.length; i++) {
				tmpKV = paramsKandV[i].split("\\=");

				if (tmpKV[0].equalsIgnoreCase("DS_ID")
						|| tmpKV[0].equalsIgnoreCase("NAME")) {
					whereKey.append(" and " + tmpKV[0] + "=? ");
					whereKeyValues.append(tmpKV[1] + "|");
				} else {// 不可更新
					if (tmpKV.length == 2) {
						// 将等号前面的拼接
						keyStr.append(tmpKV[0] + "=?,");
						keyValues.append(tmpKV[1] + "|");
					}
				}
			}
			// 拼接SQL
			if (keyStr.toString().trim().equals("")) {
				returnObject.setMsg("没有修改过的字段");
				throw new RuntimeException("没有修改过的字段");
			}
			if (whereKey.toString().trim().equals("")) {
				returnObject.setMsg("更新记录的条件为空，无法更新操作！");
				throw new RuntimeException("更新记录的条件为空，无法更新操作！");
			}
			String sqlKeys = keyStr.toString().substring(0,
					keyStr.toString().length() - 1);
			String whereSql = whereKey.toString().substring(0,
					whereKey.toString().length() - 1);
			String[] valuesArr = keyValues.toString().split("\\|");
			String[] whereValue = whereKeyValues.toString().split("\\|");
			String sqlText = " update " + sysTName + " set " + sqlKeys
					+ " where 1=1 " + whereSql;
			// 执行sql
			boolean flag = uiService.updateObject(sqlText, valuesArr,
					whereValue);
			returnObject.setMsg("已经成功修改！");
			return returnObject;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
}